# -*- coding: latin-1 -*-
from datetime import date, datetime
from calendar import monthrange
from tjango.apps.formapago.models import *
from django import forms

class CreditCardField(forms.IntegerField):
	def __init__(self, *args, **kwargs):
		super(CreditCardField, self).__init__(*args, **kwargs)
		self.widget = forms.PasswordInput()

	def clean(self, value):
		"""Check if given CC number is valid and one of the
		   card types we accept"""
		if value and (len(value) < 13 or len(value) > 16):
			raise forms.ValidationError("Ingrese un número de tarjeta válido")
		return super(CreditCardField, self).clean(value)


class CCExpWidget(forms.MultiWidget):
	""" Widget containing two select boxes for selecting the month and year"""
	def decompress(self, value):
		return [value.month, value.year] if value else [None, None]

	def format_output(self, rendered_widgets):
		html = u' / '.join(rendered_widgets)
		return u'<span style="white-space: nowrap">%s</span>' % html


class CCExpField(forms.MultiValueField):
	EXP_MONTH = [(x, x) for x in xrange(1, 13)]
	EXP_YEAR = [(x, x) for x in xrange(date.today().year,
									   date.today().year + 15)]
	default_error_messages = {
		'invalid_month': u'Ingrese un mes válido.',
		'invalid_year': u'Ingrese un año válido.',
	}

	def __init__(self, *args, **kwargs):
		errors = self.default_error_messages.copy()
		if 'error_messages' in kwargs:
			errors.update(kwargs['error_messages'])
		fields = (
			forms.ChoiceField(choices=self.EXP_MONTH,
				error_messages={'invalid': errors['invalid_month']}),
			forms.ChoiceField(choices=self.EXP_YEAR,
				error_messages={'invalid': errors['invalid_year']}),
		)
		super(CCExpField, self).__init__(fields, *args, **kwargs)
		self.widget = CCExpWidget(widgets =
			[fields[0].widget, fields[1].widget])

	def clean(self, value):
		exp = super(CCExpField, self).clean(value)
		if date.today() > exp:
			raise forms.ValidationError(
			"La tarjeta ya ha vencido.")
		return exp

	def compress(self, data_list):
		if data_list:
			if data_list[1] in forms.fields.EMPTY_VALUES:
				error = self.error_messages['invalid_year']
				raise forms.ValidationError(error)
			if data_list[0] in forms.fields.EMPTY_VALUES:
				error = self.error_messages['invalid_month']
				raise forms.ValidationError(error)
			year = int(data_list[1])
			month = int(data_list[0])
			# find last day of the month
			day = monthrange(year, month)[1]
			return date(year, month, day)
		return None


class TarjetaForm(forms.ModelForm):
	numero = CreditCardField(required = True, label = "Número de tarjeta")
	vencimiento = CCExpField(required = True, label = "Vencimiento")
	#código = forms.IntegerField(required = True, label = "Código",  max_value = 9999, widget = forms.TextInput(attrs={'size': '4'}))

	class Meta:	
		model = Tarjeta

	def __init__(self, *args, **kwargs):
		self.payment_data = kwargs.pop('payment_data', None)
		super(TarjetaForm, self).__init__(*args, **kwargs)

	#def clean(self):
		#cleaned = super(TarjetaForm, self).clean()
		#if not self.errors:
		#	if not cleaned['tipo'].check_cantidad_digitos(cleaned['numero']):
		#		raise forms.ValidationError('El número de tarjeta no tiene la cantidad de dígitos correcto')
		#	if not cleaned['tipo'].check_comienzo(cleaned['numero']):
		#		raise forms.ValidationError('El número de tarjeta no corresponde a ese tipo')
		#	result = self.process_payment()
		#	if result and result[0] == 'Card declined':
		#		raise forms.ValidationError('Your credit card was declined.')
		#	elif result and result[0] == 'Processing error':
		#		raise forms.ValidationError(
		#			'We encountered the following error while processing '+\
		#			'your credit card: '+result[1])
		#return cleaned

	def process_payment(self):
		if self.payment_data:
			# don't process payment if payment_data wasn't set
			datadict = self.cleaned_data
			datadict.update(self.payment_data)

			from virtualmerchant import VirtualMerchant
			vmerchant = VirtualMerchant(datadict)

			return vmerchant.process_virtualmerchant_payment()
			
	def titulo(self):
		return "Tarjeta de Crédito"			

class CuentaBancariaForm(forms.ModelForm):
	class Meta:	
		model = CuentaBancaria

	def titulo(self):
		return "Débito en CBU"
